package com.hujf.flink.calc;

import com.hujf.flink.stock.StockPrice;
import com.hujf.flink.stock.StockSource;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Author hujf
 * @Date 2022/5/26 15:04
 * @Description TODO
 */
public class most {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();
        StockSource stockSource = new StockSource("stock");
        DataStreamSource<StockPrice> stockPriceDataStreamSource = environment.addSource(stockSource);

        SingleOutputStreamOperator<Long> volume = stockPriceDataStreamSource.keyBy(e->"time").countWindow(5)
                .aggregate(new AggregateFunction<StockPrice, Tuple2<Long,Long>, Long>() {

                    @Override
                    public Tuple2<Long, Long> createAccumulator() {
                        return new Tuple2<>(0L,0L);
                    }

                    @Override
                    public Tuple2<Long, Long> add(StockPrice value, Tuple2<Long, Long> accumulator) {
                        return new Tuple2<>(value.getVolume()+accumulator.f0,accumulator.f1+1);
                    }

                    @Override
                    public Long getResult(Tuple2<Long, Long> accumulator) {
                         return (accumulator.f0)/accumulator.f1;
                    }

                    @Override
                    public Tuple2<Long, Long> merge(Tuple2<Long, Long> a, Tuple2<Long, Long> b) {
                        return new Tuple2<>(a.f0+b.f0,a.f1+b.f1);
                    }
                });

        volume.print();

        environment.execute();
    }
}
